import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import { getAddressNameByCode } from '@/utils/utils';

import {
  Table,
  Input,
  Button,
  Modal,
  Row,
  Col,
} from 'antd';

export interface AddGardenModalProps {
  dispatch?: Dispatch<any>;
  gardenModel: boolean;
  hideGardenModel: any;
  saveGardens: any;
  gardenList?: [],
}

interface AddGardenModalState {
  loading?: boolean;
  name: string,
  current: number,
  pageSize: number | undefined,
  selectedRowKeys: any,
}

@connect(({ partnerFranchiseeEdit, loading }: any) => ({
  gardenList: partnerFranchiseeEdit.gardenList,
  loading: loading.effects['partnerGardenModel/fetch'],
}))

class AddGardenModal extends React.Component<AddGardenModalProps, AddGardenModalState> {
  columns = [
    {
      title: '社区名称',
      dataIndex: 'name',
      width: '33.33%',
    },
    {
      title: '物业',
      dataIndex: 'address',
      width: '33.33%',
    },
    {
      title: '地区',
      width: '33.33%',
      dataIndex: 'parea_code',
      render: (text: any, record: any) => (
        <div>
          {getAddressNameByCode({
            pareaCode: text,
            caredCode: record.carea_code,
            dareaCode: record.darea_code,
          })}
        </div>
      ),
    },
  ];

  state: AddGardenModalState = {
    loading: false,
    name: '',
    current: 1,
    pageSize: 5,
    selectedRowKeys: [],
  }

  /**
   * 输入社区名称
  */
  handleChangeName = (event:any) => this.setState({ name: event.target.value });

  /**
   * 回车查询
   */
  handleKeyDown = (event:any) => {
    if (event.keyCode === 13) this.fetchGardenList();
  }

  /**
   * 查询
   */
  handleSearch = () => this.setState({ current: 1 }, () => this.fetchGardenList());

  // 获取社区数据
  fetchGardenList = () => {
    const { name, current: pageNum, pageSize: numPerPage } = this.state;

    const { dispatch } = this.props;
    if (dispatch) {
      dispatch({
        type: 'partnerFranchiseeEdit/fetchGardensByName',
        payload: { name, pageNum, numPerPage },
      });
    }
  }

  // 分页和选择页码
  onSizeChange = (current: number, pageSize: number | undefined) => {
    this.setState({ current, pageSize }, () => this.fetchGardenList());
  }

  // 选中项发生变化
  onSelectChange = (selectedRowKeys: any) => this.setState({ selectedRowKeys });

  /**
   * 添加社区
   */
  handleAddGarden = () => {
    const { selectedRowKeys } = this.state;
    const { gardenList = [] } = this.props;
    const gardens = gardenList
      .filter((garden: { id: number }) => selectedRowKeys.find((id: number) => id === garden.id));

    const { saveGardens } = this.props;
    saveGardens(gardens);

    const { hideGardenModel } = this.props;
    hideGardenModel();
  }

  render() {
    const {
      gardenList = [],
      gardenModel,
      hideGardenModel,
    } = this.props;

    const {
      loading,
      pageSize,
      current,
      selectedRowKeys,
    } = this.state;

    const pagination = gardenList ? {
      total: gardenList.length,
      pageSize,
      current: current || 1,
      onChange: this.onSizeChange,
      showSizeChanger: true,
      pageSizeOptions: ['5', '10'],
      onShowSizeChange: this.onSizeChange,
    } : {};

    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };

    return (
      <Modal
        title="选择社区"
        width={600}
        visible={gardenModel}
        onOk={this.handleAddGarden}
        onCancel={hideGardenModel}
      >

        <Row
          gutter={{ md: 8, lg: 24, xl: 48 }}
          style={{
            marginBottom: 16,
            display: 'flex',
            justifyContent: 'end',
          }}
        >
          <Col span={19}>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <div style={{ width: 120 }}>合作商名称:</div>
              <Input
                placeholder="请输入"
                onChange={this.handleChangeName}
                onKeyDown={this.handleKeyDown}
              />
            </div>
          </Col>
          <Col span={5} style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <Button
              type="primary"
              onClick={this.handleSearch}
            >查询
            </Button>
          </Col>
        </Row>

        <Table
          rowKey="id"
          loading={loading}
          columns={this.columns}
          dataSource={gardenList}
          className="addTableGarden tableList statementTable"
          pagination={pagination}
          rowSelection={rowSelection}
        />
      </Modal>
    );
  }
}

export default AddGardenModal;
